package org.xxpay.manage.config.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.entity.PayAlizftSettRecord;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: pangxioayu
 * @date: 20/10/21
 * @description: 支付宝支付通
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/pay_alizft_sett_record")
public class PayAlizftSettRecordController extends BaseController {

    @Autowired
    RpcCommonService rpcCommonService;

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        PayAlizftSettRecord condition = getObject(param, PayAlizftSettRecord.class);
        Long count = commonService.payAlizftSettRecordService.count(condition);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<PayAlizftSettRecord> infoList = commonService.payAlizftSettRecordService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), condition);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(infoList, count.intValue()));
    }


    /** 重新发起结算 **/
    @RequestMapping("/retry")
    @ResponseBody
    @MethodLog( remark = "重新发起直付通结算")
    public ResponseEntity<?> retry(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);

        Long recordId = getLongRequired(param, "recordId");
        PayAlizftSettRecord dbRecord = commonService.payAlizftSettRecordService.findById(recordId);
        if(dbRecord == null || dbRecord.getStatus() != MchConstant.ALIZFT_SETT_STATUS_FAIL){
            throw new ServiceException(RetEnum.RET_COMM_RECORD_NOT_EXIST);
        }

        PayAlizftSettRecord updateRecord = new PayAlizftSettRecord();
        updateRecord.setStatus(MchConstant.ALIZFT_SETT_STATUS_NOT); //更改为未结算状态
        updateRecord.setId(recordId);
        commonService.payAlizftSettRecordService.update(updateRecord);

        rpcCommonService.rpcXxPayPayService.alizftTradeSettleConfirmRetry(recordId);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess());
    }



}
